package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB2Config;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.PcbNewTechnologyService;
import com.sailfish.springbootdemo.service.db2.S3UploadFileService;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.mongodb.core.aggregation.ConvertOperators;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PcbNewTechnologyServiceImpl implements PcbNewTechnologyService {

    @Autowired
    PcbNewTechnologyPicDao pcbNewTechnologyPicDao;
    @Autowired
    PcbNewTechnologyInfoDao pcbNewTechnologyInfoDao;
    @Autowired
    PcbCapacityDataApproveDao pcbCapacityDataApproveDao;
    @Autowired
    PcbCapacityApproveDetailDao pcbCapacityApproveDetailDao;
    @Autowired
    PcbCapacityApproveDetailFileDao pcbCapacityApproveDetailFileDao;
    @Autowired
    PcbApproveProcessDao pcbApproveProcessDao;
    @Autowired
    PcbNewTechnologyParamDao pcbNewTechnologyParamDao;
    @Autowired
    PcbNewTechnologyLibraryDao pcbNewTechnologyLibraryDao;
    @Autowired
    PcbNewTechnologyFactoryDao pcbNewTechnologyFactoryDao;
    @Autowired
    PcbNewTechnologyFileDao pcbNewTechnologyFileDao;
    @Autowired
    OperateService operateService;
    @Autowired
    PcbApproveProcessDao approveProcessDao;
    @Autowired
    PcbApproveConfigDao pcbApproveConfigDao;
    @Autowired
    UserDao userDao;
    @Autowired
    ThirdApiService thirdApiService;
    @Autowired
    S3UploadFileService s3UploadFileService;

    @Value("${personal.config.env}")
    String env;

    @Override
    public List<PcbNewTechnologyParam> getAllPcbNewTechnologyParam(PcbNewTechnologyParam param) {
        return pcbNewTechnologyParamDao.getAllByLimit(param);
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdatePcbNewTechnologyParam(PcbNewTechnologyParam param) {
        try {
            String userId = UserHeaderHolder.getUserId();
            if (param.getParamId() == null) {
                PcbNewTechnologyParam search = new PcbNewTechnologyParam();
                search.setParamName(param.getParamName());
                List<PcbNewTechnologyParam> allByLimit = pcbNewTechnologyParamDao.getAllByLimit(search);
                if (allByLimit.stream().count() > 0) {
                    return ResultUtil.error(500, "重复添加", "", null);
                } else {
                    int count = pcbNewTechnologyParamDao.insert(param);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术参数设置", 1, 1, new Date(), null, JSONObject.toJSONString(param)));
                        return ResultUtil.success(param);
                    }
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            } else {
                PcbNewTechnologyParam oldData = pcbNewTechnologyParamDao.getAllById(param.getParamId());
                int count = pcbNewTechnologyParamDao.update(param);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术参数设置", 3, 1, new Date(), JSONObject.toJSONString(oldData), JSONObject.toJSONString(param)));
                    return ResultUtil.success(param);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result deletePcbNewTechnologyParam(Integer id) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbNewTechnologyParam oldData = pcbNewTechnologyParamDao.getAllById(id);
            int count = pcbNewTechnologyParamDao.delete(id);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术参数设置", 2, 1, new Date(), JSONObject.toJSONString(oldData), null));
                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result checkPcbNewTechnologyHasData(Integer id) {
        PcbNewTechnologyParam pcbNewTechnologyParam = pcbNewTechnologyParamDao.getAllById(id);
        if (pcbNewTechnologyParam != null) {
            String paramKey = pcbNewTechnologyParam.getParamKey();
            PcbNewTechnologyLibrary search = new PcbNewTechnologyLibrary();
            search.setParamKey(paramKey);
            List<PcbNewTechnologyLibrary> allByLimit = pcbNewTechnologyLibraryDao.getAllByLimit(search);
            if (allByLimit.size() > 0) {
                return ResultUtil.success(false);
            } else {
                return ResultUtil.success(true);
            }
        }
        return ResultUtil.success(true);
    }

    @Override
    public Map<String, NewTechnologyInfo> getAllPcbNewTechnologyLibrary(List<PcbNewTechnologyLibrary> params, String approveStatus) {
        String userId = UserHeaderHolder.getUserId();
        List<PcbNewTechnologyLibrary> list;
        List<String> list_rowKey = new ArrayList<>();
        if (params == null) {
            if (!StringUtils.isBlank(approveStatus)) {
                list_rowKey = pcbNewTechnologyFactoryDao.getRowKeyByLimit(null, approveStatus, null);
                if (list_rowKey == null || list_rowKey.size() == 0) {
                    return null;
                }
                list = pcbNewTechnologyLibraryDao.getByRowKey(list_rowKey);
            } else {
                list = pcbNewTechnologyLibraryDao.getAllByLimit(null);
            }
        } else {
            for (int i = 0; i < params.size(); i++) {
                List<String> temp = pcbNewTechnologyLibraryDao.getBySearch(params.get(i));
                if (i == 0) {
                    list_rowKey = temp;
                } else {
                    list_rowKey.retainAll(temp);
                }
            }

            if (list_rowKey == null || list_rowKey.size() == 0) {
                return null;
            }
            list = pcbNewTechnologyLibraryDao.getByRowKey(list_rowKey);
        }

        Map<String, List<PcbNewTechnologyLibrary>> collect = list.stream().collect(Collectors.groupingBy(PcbNewTechnologyLibrary::getRowKey));
        Map<String, NewTechnologyInfo> newTechnologyInfoHashMap = new HashMap<>();
        for (String key : collect.keySet()) {
            List<PcbNewTechnologyLibrary> pcbMaterialData = collect.get(key);
            for (int i = 0; i < pcbMaterialData.size(); i++) {
                if (pcbMaterialData.get(i).getParamType() != null && (pcbMaterialData.get(i).getParamType() == 3 || pcbMaterialData.get(i).getParamType() == 7)) {
                    List<PcbNewTechnologyFile> pcbNewTechnologyFileList = pcbNewTechnologyFileDao.getAllByLimit(key, pcbMaterialData.get(i).getParamKey(), null);
                    for (int a = 0; a < pcbNewTechnologyFileList.size(); a++) {
                        final String url = pcbNewTechnologyFileList.get(a).getUrl();
                        if (!StringUtils.isBlank(url)) {
                            String base64Image = s3UploadFileService.getImageBase64FromUrl(url);
                            pcbNewTechnologyFileList.get(a).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                        }
                    }
                    pcbMaterialData.get(i).setPcbNewTechnologyFileList(pcbNewTechnologyFileList);
                }
            }
            NewTechnologyInfo newTechnologyInfo = new NewTechnologyInfo();
            newTechnologyInfo.setPcbNewTechnologyLibraryList(pcbMaterialData);
            PcbNewTechnologyFactory pcbNewTechnologyFactory = pcbNewTechnologyFactoryDao.getByRowKey(key);
            PcbCapacityDataApprove search = new PcbCapacityDataApprove();
            search.setRowKey(key);
            search.setStatus(1);
            search.setFlowType(2);
            List<PcbCapacityDataApprove> pcbCapacityDataApproveList = pcbCapacityDataApproveDao.getByLimit(search);
            if (pcbCapacityDataApproveList.size() > 0) {
                newTechnologyInfo.setApproveStatus(pcbCapacityDataApproveList.get(0).getApproveStatus());
            }
            newTechnologyInfo.setNewTechnologyStatus(pcbNewTechnologyFactory.getNewTechnologyStatus());
            newTechnologyInfo.setResponsibilityUserId(pcbNewTechnologyFactory.getResponsibilityUserId());
            newTechnologyInfo.setResponsibilityUserName(pcbNewTechnologyFactory.getResponsibilityUserName());
//            newTechnologyInfo.setApproveStatus(pcbNewTechnologyFactory.getApproveStatus());
//            if(pcbNewTechnologyFactory.getApproveStatus().equals("审批中") ){
//                if(Integer.parseInt(userId) == pcbNewTechnologyFactory.getApproveUserId()){
//                    newTechnologyInfo.setAllowApprove(true);
//                }
//                else {
//                    newTechnologyInfo.setAllowApprove(false);
//                }
//            }
            newTechnologyInfo.setApproveUserId(pcbNewTechnologyFactory.getApproveUserId());
            if (pcbNewTechnologyFactory.getApproveUserId() != null) {
                User user = userDao.getUserInfoById(pcbNewTechnologyFactory.getApproveUserId());
                newTechnologyInfo.setApproveUser(user);
            }
            newTechnologyInfo.setRemark(pcbNewTechnologyFactory.getRemark());
            newTechnologyInfoHashMap.put(key, newTechnologyInfo);
        }
        return newTechnologyInfoHashMap;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdatePcbNewTechnologyLibrary(String data) {
        try {
            String userId = UserHeaderHolder.getUserId();
            JSONObject jsonObject = JSONObject.parseObject(data);
            String mode = jsonObject.getString("mode");
            JSONArray jsonArray = jsonObject.getJSONArray("pcbTemplateList");
            if (jsonArray == null || jsonArray.size() == 0) {
                return ResultUtil.error(500, "pcbTemplateList 为空", "pcbTemplateList is null", null);
            }

            List<PcbNewTechnologyLibrary> entities = new ArrayList<>();
            String rowKey;
            if (mode.equals("update")) {
                rowKey = jsonObject.getString("rowKey");
            } else {
                rowKey = String.valueOf(System.currentTimeMillis());
            }

            for (int i = 0; i < jsonArray.size(); i++) {
                PcbNewTechnologyLibrary pcbNewTechnologyLibrary = new PcbNewTechnologyLibrary();
                JSONObject jo = (JSONObject) jsonArray.get(i);

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String paramKey = jo.get("pcbParamKey") == null ? null : jo.get("pcbParamKey").toString();
                pcbNewTechnologyLibrary.setParamKey(paramKey);

                Integer paramType = jo.get("paramType") == null ? null : Integer.parseInt(jo.get("paramType").toString());
                pcbNewTechnologyLibrary.setParamType(paramType);
                if (paramType != 3 && paramType != 7) {
                    pcbNewTechnologyLibrary.setParamValue(jo.get("pcbParamValue") == null ? null : jo.get("pcbParamValue").toString());
                } else {
                    List<PcbNewTechnologyFile> oldData = pcbNewTechnologyFileDao.getAllByLimit(rowKey, paramKey, null);
                    int count = pcbNewTechnologyFileDao.deleteByRowKey(rowKey, paramKey);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术库文件", 2, 1, new Date(), JSONObject.toJSONString(oldData), null));
                    }
                    JSONArray pcbParamValueArray = jo.getJSONArray("pcbParamValue");
                    String paramValue = "";
                    if (pcbParamValueArray != null) {
                        for (int n = 0; n < pcbParamValueArray.size(); n++) {
                            JSONObject joPic = (JSONObject) pcbParamValueArray.getJSONObject(n);
                            PcbNewTechnologyFile file = new PcbNewTechnologyFile();
                            file.setRowKey(rowKey);
                            file.setParamKey(paramKey);
                            String filename = joPic.get("oldName") == null ? null : joPic.get("oldName").toString();
                            file.setFileName(filename);
                            String url = joPic.get("url2") == null ? null : joPic.get("url2").toString();
                            file.setUrl(url);
                            file.setFileExtend(filename.substring(filename.lastIndexOf(".") + 1));
                            String relatePath = joPic.get("picRelatePath") == null ? null : joPic.get("picRelatePath").toString();
                            file.setFileRelatePath(relatePath);
                            file.setFileType(paramType);
                            file.setCreateTime(new Date());
                            file.setCreateUser(userId);
                            String secretKey = joPic.get("secretKey") == null ? null : joPic.get("secretKey").toString();
                            String fileSid = joPic.get("fileSid") == null ? null : joPic.get("fileSid").toString();
                            file.setFileSid(fileSid);
                            file.setSecretKey(secretKey);
                            paramValue += relatePath + ",";
                            count = pcbNewTechnologyFileDao.insert(file);
                            if (count > 0) {
                                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术库文件", 1, 1, new Date(), null, JSONObject.toJSONString(file)));
                            } else {
                                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                            }
                        }
                    }

                    pcbNewTechnologyLibrary.setParamValue(paramValue);
                }
                pcbNewTechnologyLibrary.setSort(jo.get("sort") == null ? null : Integer.parseInt(jo.get("sort").toString()));
                pcbNewTechnologyLibrary.setStatus(jo.get("status") == null ? null : Integer.parseInt(jo.get("status").toString()));

                if (jo.get("pcbLibraryId") == null) {
                    pcbNewTechnologyLibrary.setCreateTime(new Date());
                    pcbNewTechnologyLibrary.setRowKey(rowKey);
                    int count = pcbNewTechnologyLibraryDao.insert(pcbNewTechnologyLibrary);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术库", 1, 1, new Date(), null, JSONObject.toJSONString(pcbNewTechnologyLibrary)));
                    } else {
                        return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                    }
                } else {
                    pcbNewTechnologyLibrary.setPcbLibraryId(jo.get("pcbLibraryId") == null ? null : Integer.parseInt(jo.get("pcbLibraryId").toString()));
                    pcbNewTechnologyLibrary.setCreateTime(jo.get("createTime") == null ? null : format.parse(jo.get("createTime").toString()));
                    pcbNewTechnologyLibrary.setUpdateTime(new Date());
                    List<PcbNewTechnologyLibrary> oldData = pcbNewTechnologyLibraryDao.getAllById(pcbNewTechnologyLibrary.getPcbLibraryId());
                    int count = pcbNewTechnologyLibraryDao.update(pcbNewTechnologyLibrary);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术库", 3, 1, new Date(), JSONObject.toJSONString(oldData), JSONObject.toJSONString(pcbNewTechnologyLibrary)));
                    } else {
                        return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                    }
                }
                entities.add(pcbNewTechnologyLibrary);
            }

            String newTechnologyStatus = jsonObject.getString("pcbTechnologyStatus");
            Integer responsibilityUserId = jsonObject.getInteger("responsibilityUserId");
            String responsibilityUserName = jsonObject.getString("responsibilityUserName");
            if (mode.equals("add")) {
                PcbNewTechnologyFactory pcbNewTechnologyFactory = new PcbNewTechnologyFactory();
                pcbNewTechnologyFactory.setRowKey(rowKey);
                pcbNewTechnologyFactory.setNewTechnologyStatus(newTechnologyStatus);//待提交
                pcbNewTechnologyFactory.setResponsibilityUserName(responsibilityUserName);
                pcbNewTechnologyFactory.setResponsibilityUserId(responsibilityUserId);
                pcbNewTechnologyFactory.setApproveStatus("待分配");
                pcbNewTechnologyFactory.setCreateTime(new Date());
                pcbNewTechnologyFactory.setCreateUser(userId);

                Integer insert = pcbNewTechnologyFactoryDao.insert(pcbNewTechnologyFactory);
                if (insert > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术状态表", 1, 1, new Date(), null, JSONObject.toJSONString(pcbNewTechnologyFactory)));
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            } else {
                PcbNewTechnologyFactory pcbNewTechnologyFactory = new PcbNewTechnologyFactory();
                pcbNewTechnologyFactory.setRowKey(rowKey);
                pcbNewTechnologyFactory.setNewTechnologyStatus(newTechnologyStatus);//待提交
                pcbNewTechnologyFactory.setResponsibilityUserName(responsibilityUserName);
                pcbNewTechnologyFactory.setResponsibilityUserId(responsibilityUserId);
                pcbNewTechnologyFactory.setApproveStatus("待分配");
                pcbNewTechnologyFactory.setUpdateTime(new Date());
                pcbNewTechnologyFactory.setUpdateUser(userId);
                PcbNewTechnologyFactory oldData = pcbNewTechnologyFactoryDao.getByRowKey(rowKey);
                Integer insert = pcbNewTechnologyFactoryDao.updateStatus(pcbNewTechnologyFactory);
                if (insert > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术状态表", 3, 1, new Date(), JSONObject.toJSONString(oldData), JSONObject.toJSONString(pcbNewTechnologyFactory)));
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            }
            return ResultUtil.success(entities);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result deletePcbNewTechnologyLibrary(String row_key, String paramKey) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbNewTechnologyLibrary search = new PcbNewTechnologyLibrary();
            search.setRowKey(row_key);
            List<PcbNewTechnologyLibrary> oldData = pcbNewTechnologyLibraryDao.getAllByLimit(search);
            int count = pcbNewTechnologyLibraryDao.delete(row_key);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术库", 2, 1, new Date(), JSONObject.toJSONString(oldData), null));
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }

            PcbNewTechnologyFactory oldData2 = pcbNewTechnologyFactoryDao.getByRowKey(row_key);
            Integer deleteByRowKey = pcbNewTechnologyFactoryDao.deleteByRowKey(row_key);
            if (deleteByRowKey > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术状态表", 2, 1, new Date(), JSONObject.toJSONString(oldData2), null));
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result updatePcbNewTechnologyStatus(String rowKey, Integer responsibilityUserId, String responsibilityUserName,
                                               String newTechnologyStatus, String remark, String approveStatus, Integer approverUserId) {
        try {
            String userId = UserHeaderHolder.getUserId();
            int flowtype = 2;
            try {
                int factoryId = -1;
                PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowtype, null, null);
                if (approveConfig == null) {
                    return ResultUtil.error(500, "请先配置" + "相关流程的审核人员", "Fail", null);
                }
                PcbCapacityDataApprove search = new PcbCapacityDataApprove();
                search.setRowKey(rowKey);
                search.setFlowType(flowtype);
                search.setStatus(1);
                search.setFactoryId(factoryId);
                List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);

                if (byLimit.size() > 0) {
                    for (int i = 0; i < byLimit.size(); i++) {
                        if (byLimit.get(i).getApproveStatus().equals(DB2Config.CapacityDataStatus_Wancheng)) {
                            byLimit.get(i).setStatus(2);//将之前的都作废
                            pcbCapacityDataApproveDao.update(byLimit.get(i));
                        } else {
                            return ResultUtil.error(500, "当前行有未处理完成的任务", "", null);
                        }
                    }
                }
                //自动创建流程
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String currentDate = sdf.format(new Date());
                PcbCapacityDataApprove byFlowNum = pcbCapacityDataApproveDao.getByFlowNum(currentDate);
                int currentSeq = 0;
                String flowNum = "";
                if (byFlowNum != null) {
                    currentSeq = byFlowNum.getSeq();
                }
                currentSeq++;
                //添加审批记录
                flowNum = currentDate + String.format("%05d", currentSeq);
                PcbCapacityDataApprove pcbCapacityDataApprove1 = new PcbCapacityDataApprove();
                pcbCapacityDataApprove1.setFlowNum(flowNum);
                pcbCapacityDataApprove1.setSeq(currentSeq);
                pcbCapacityDataApprove1.setFlowType(flowtype);
                pcbCapacityDataApprove1.setFactoryId(factoryId);
                pcbCapacityDataApprove1.setApproveStatus(DB2Config.CapacityDataStatus_Chuliren);
                pcbCapacityDataApprove1.setCreateTime(new Date());
                pcbCapacityDataApprove1.setCreateUser(userId);
                pcbCapacityDataApprove1.setApproveUserId(approveConfig.getOperator2().toString());
                pcbCapacityDataApprove1.setStatus(1);
                pcbCapacityDataApprove1.setRowKey(rowKey);
                pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove1);
                //添加审批详情
                PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
                pcbCapacityApproveDetail.setFlowType(flowtype);
                pcbCapacityApproveDetail.setDataId(pcbCapacityDataApprove1.getId());
                pcbCapacityApproveDetail.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                pcbCapacityApproveDetail.setApplyUserId(Integer.parseInt(userId));
                pcbCapacityApproveDetail.setDepartmentId(null);
                pcbCapacityApproveDetail.setSonFactoryId(null);
                pcbCapacityApproveDetail.setFileIds(null);
                pcbCapacityApproveDetail.setRemark(null);
                pcbCapacityApproveDetail.setCreateTime(new Date());
                pcbCapacityApproveDetail.setCreateUser(userId);
                pcbCapacityApproveDetail.setStatus(1);
                pcbCapacityApproveDetail.setSort(100);
                pcbCapacityApproveDetail.setNextNodeUserId(approveConfig.getOperator2());
                pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail);
                //添加审批过程记录
                PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
                pcbApproveProcess.setApproveType(flowtype);
                pcbApproveProcess.setDataId(pcbCapacityDataApprove1.getId());
                pcbApproveProcess.setOldStatus("");
                pcbApproveProcess.setNewStatus(DB2Config.CapacityDataStatus_CreateFlow);
                pcbApproveProcess.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                pcbApproveProcess.setCreateTime(new Date());
                pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
                pcbApproveProcess.setApplyToId(null);
                pcbApproveProcessDao.insert(pcbApproveProcess);
                //添加审批详情
                PcbCapacityApproveDetail pcbCapacityApproveDetail2 = new PcbCapacityApproveDetail();
                pcbCapacityApproveDetail2.setFlowType(flowtype);
                pcbCapacityApproveDetail2.setDataId(pcbCapacityDataApprove1.getId());
                pcbCapacityApproveDetail2.setApproveNode(DB2Config.CapacityDataStatus_Chuliren);
                pcbCapacityApproveDetail2.setApplyUserId(Integer.parseInt(userId));
                pcbCapacityApproveDetail2.setSonFactoryId(null);
                pcbCapacityApproveDetail2.setCreateTime(new Date());
                pcbCapacityApproveDetail2.setCreateUser(userId);
                pcbCapacityApproveDetail2.setStatus(1);
                pcbCapacityApproveDetail2.setSort(100);
                pcbCapacityApproveDetail2.setNextNodeUserId(approveConfig.getOperator3());
                pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail2);
                //添加审批过程记录
                PcbApproveProcess pcbApproveProcess2 = new PcbApproveProcess();
                pcbApproveProcess2.setApproveType(flowtype);
                pcbApproveProcess2.setDataId(pcbCapacityDataApprove1.getId());
                pcbApproveProcess2.setOldStatus(DB2Config.CapacityDataStatus_CreateFlow);
                pcbApproveProcess2.setNewStatus(DB2Config.CapacityDataStatus_Chuliren);
                pcbApproveProcess2.setApproveNode(DB2Config.CapacityDataStatus_Chuliren);
                pcbApproveProcess2.setCreateTime(new Date());
                pcbApproveProcess2.setApplyToId(Integer.parseInt(userId));
                pcbApproveProcessDao.insert(pcbApproveProcess2);

                User userInfo = userDao.getUserInfoById(Integer.parseInt(userId));
                try {
                    if (!StringUtils.isBlank(env) && env.equals("h3c_pro")) {
                        List<MailAddress> mailAddressList = new ArrayList<>();
                        if(userInfo.getEmail().contains(",")){
                            String[] emailsArr = userInfo.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(userInfo.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }

                        thirdApiService.sendMail(userInfo.getUserName(), "PCB新技术数据审批", "PCB新技术数据审批",
                                "您有待处理的任务，请及时处理", "10086", mailAddressList, null, null, null, null, 2, null);

                        System.out.println("send mail success");
                    }
                } catch (Exception e) {
                    System.out.println("send mail error :" + e.getMessage());
                }

                return ResultUtil.success(null);
            } catch (Exception e) {
                e.printStackTrace();
                ;
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insert(PcbNewTechnologyInfo param) {
        try {
            String userId = UserHeaderHolder.getUserId();
            int count = pcbNewTechnologyInfoDao.insert(param);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术管理", 1, 1, new Date(), null, JSONObject.toJSONString(param)));
            }
            List<PcbNewTechnologyPic> picList = param.getPicList();
            for (PcbNewTechnologyPic item : picList) {
                item.setPcbNewTechnologyInfoId(param.getPcbNewTechnologyInfoId());
            }
            PcbNewTechnologyPic picSearch = new PcbNewTechnologyPic();
            picSearch.setPcbNewTechnologyInfoId(param.getPcbNewTechnologyInfoId());
            List<PcbNewTechnologyPic> allByLimit = pcbNewTechnologyPicDao.getAllByLimit(picSearch);
            String oldData = JSONObject.toJSONString(allByLimit);
            int count2 = pcbNewTechnologyPicDao.deleteByInfoId(param.getPcbNewTechnologyInfoId());
            if (count2 > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术管理图片", 2, 1, new Date(), oldData, null));
            }
            if (picList != null && picList.size() > 0) {
                for (int i = 0; i < picList.size(); i++) {
                    picList.get(i).setCreateTime(new Date());
                    picList.get(i).setCreateUser(userId);
                }
                if (picList != null && picList.size() > 0) {
                    int count3 = pcbNewTechnologyPicDao.insertBatch(picList);
                    if (count3 > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术管理图片", 1, 1, new Date(), null, JSONObject.toJSONString(picList)));
                    }
                }

            }

            return ResultUtil.success(param);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }


    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result updateStatus(String status, Integer id, Integer approveUser, String remark) {
        try {
            if (status == "待分配" && approveUser == null) {
                return ResultUtil.error(500, "审批人为空", "approveUser is null", null);
            }
            String userId = UserHeaderHolder.getUserId();
            PcbNewTechnologyInfo pcbNewTechnologyInfo = new PcbNewTechnologyInfo();
            pcbNewTechnologyInfo.setApproveStatus(status);
            pcbNewTechnologyInfo.setPcbNewTechnologyInfoId(id);
            pcbNewTechnologyInfo.setApproveUserId(approveUser);
            pcbNewTechnologyInfo.setUpdateTime(new Date());
            PcbNewTechnologyInfo pcbNewTechnologyInfo_old = pcbNewTechnologyInfoDao.getAllById(id);
            String oldData = JSONObject.toJSONString(pcbNewTechnologyInfo_old);
            int count = pcbNewTechnologyInfoDao.update(pcbNewTechnologyInfo);
            if (count > 0) {
                PcbNewTechnologyInfo pcbNewTechnologyInfo_new = pcbNewTechnologyInfoDao.getAllById(id);
                PcbApproveProcess approveProcess = new PcbApproveProcess();
                approveProcess.setApproveType(2);
                approveProcess.setDataId(id);
                approveProcess.setApproveUserId(Integer.parseInt(userId));
                approveProcess.setOldStatus(pcbNewTechnologyInfo_old.getApproveStatus());
                approveProcess.setNewStatus(status);
                approveProcess.setCreateTime(new Date());
                approveProcess.setRemark(remark);
                approveProcessDao.insert(approveProcess);
                String newData = JSONObject.toJSONString(pcbNewTechnologyInfo_new);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB新技术管理", 3, 1, new Date(), oldData, newData));
                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public PcbNewTechnologyFile getFileById(Integer id) {
        return pcbNewTechnologyFileDao.getAllById(id);
    }



}
